// mockjs实现对接口数据的传递

import Mock from 'mockjs';

Mock.setup({
    timeout: '500-800',
});

// 拦截请求

// 用户数据数组
const userData = [
    { id: '1', username: 'admin', name:'测试', password: '12345678Aa', mailbox: '11223344@qq.com', ifused: true, role:'product'},
    { id: '2', username: 'lili', name:'测试', password: 'Aa11223344', mailbox: '12312344@qq.com', ifused: false, role:'order'},
    { id: '3', username: 'ranran', name:'测试', password: 'Aa123123', mailbox: '12312366@qq.com', ifused: false, role:'super'}
];

// login接口
Mock.mock(/\/login/, 'post', (options) => {
    const { username, password } = JSON.parse(options.body);
    console.log('拦截login接口');

    // 验证用户名和密码
    const user = userData.find(user => user.username === username && user.password === password);
    if (user) {
        // 模拟成功登录后设置本地存储
        localStorage.setItem('isLoggedIn', 'true');
        console.log(localStorage);

        return {
            status: 200,
            message: '登录成功',
            data: {
                token: 'fakeToken1234567890'
            }
        };
    } else {
        return {
            status: 401,
            message: '用户名或密码错误'
        };
    }
});

// 拦截并模拟 register 接口
Mock.mock(/\/register/, 'post', (options) => {
    const { username, password, mailbox } = JSON.parse(options.body);
    console.log('拦截register接口');

    const existingUser = userData.find(user => user.username === username || user.mailbox === mailbox);
    if (existingUser) {
        return {
            status: 400,
            message: '用户名或邮箱已存在'
        };
    } else {
        userData.push({ username, password, mailbox });
        return {
            status: 201,
            message: '注册成功'
        };
    }
});
